<?php
/**
 * @企业类
 * 1、企业列表
 * 2、企业详情
 */

namespace app\admin\controller;

use app\common\controller\HomeCommon;
use app\common\model\Label;
use think\Cache;
use think\Config;
use think\Controller;
use think\Db;
use think\Request;
use think\View;

class Company extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 添加企业 推送
     * @param Request $request
     * @return mixed
     */
    public function add(Request $request)
    {
        if ($request->isPost()){
            $data['company_name']=$request->post('company_name','','trim');
            $data['legal']=$request->post('legal','','trim');
            $data['elephone']=$request->post('elephone','','trim');
            $data['register_time']=$request->post('register_time','','trim');
            $data['register_money']=$request->post('register_money','','trim');
            $data['register_money_cg']=$request->post('register_money_cg','','trim');
            $data['email']=$request->post('email','','trim');
            $data['province_id']=$request->post('province_id',0,'intval');
            $data['city_id']=$request->post('city_id','','intval');
            $data['area_id']=$request->post('area_id','','intval');
            $data['score']=$request->post('score','','intval');
            $data['invest_score']=$request->post('invest_score','','intval');
            $data['logo']=$request->post('logo','','trim');
            $data['address']=$request->post('address','','trim');
            $data['lat']=$request->post('lat','','trim');
            $data['lng']=$request->post('lng','','trim');
            $data['create_time']=$request->post('create_time','','trim');
            $data['com_type']=$request->post('com_type',0,'intval');
            $data['park_id']=$request->post('park_id',0,'intval');
            $data['desc']=$request->post('desc','','trim');
            $data['score_1']=$request->post('score_1','','intval');
            $push=$request->post('push',2,'intval');
            /****city_str*****/
            $city=array($data['province_id'],$data['city_id'],$data['area_id']);
            $city_str=[];
            $cityModel=db('city');
            foreach ($city as $id){
                if (!empty($id)){
                    $name=$cityModel->where('id',$id)->value('city_name as name');
                    $city_str[]=compact('id','name');
                }
            }
            /****industry_str*****/
            $industry_str=[];
            $industry_ids=[];
            $industry_data=$request->post()['industry'];
            $industryModel=db('industry');
            foreach ($industry_data as $id){
                if ($id){
                    $name=$industryModel->where('id',$id)->value('industry_name as name');
                    $industry_str[]=compact('id','name');
                    array_push($industry_ids,$id);
                }
            }
            /****chain****/
            $chain_data=$request->post()['chain'];
            $chains=[];
            foreach ($chain_data as $chain_id){
                if ($chain_id){
                    array_push($chains,$chain_id);
                }
            }
            /****ipo****/
            if (isset($request->post()['ipo'])){
                $data['is_ipo']= in_array(1,$request->post()['ipo']) ? 1 :0;
                $data['is_inspect']= in_array(2,$request->post()['ipo']) ? 1 :0;
                $data['is_report']= in_array(3,$request->post()['ipo']) ? 1 :0;
                $data['is_market']= in_array(4,$request->post()['ipo']) ? 1 :0;
            }

            $data['com_type']=company_type($data['com_type']);
            $data['city_str']=json_encode($city_str);
            $data['industry_str']=json_encode($industry_str);
            $data['identification']=uniqid('xd');
            $data['status']=1;

            $chainInsert=[];
            $industryInsert=[];
            /*维护chain_name*/
            $data['chain_name']='';
            if (!empty($chains)){
                $data['chain_name']=db('chain')->where(['status'=>1,'pid'=>0,'id'=>min($chains)])->value('chain_name');
            }
            Db::startTrans();
            try {
                /****主表****/
                $company_id=Db::table('yd_companys')->insertGetId($data);
                /****chain****/
                foreach ($chains as $k=>$id){
                    $chainInsert[$k]['company_id']=$company_id;
                    $chainInsert[$k]['chain_id']=$id;
                    $chainInsert[$k]['status']=1;
                }
                Db::table('yd_companys_chain')->insertAll($chainInsert);
                /****industry****/
                foreach ($industry_ids as $k=>$id){
                    $industryInsert[$k]['company_id']=$company_id;
                    $industryInsert[$k]['industry_id']=$id;
                    $industryInsert[$k]['status']=1;
                }
                Db::table('yd_companys_industry')->insertAll($industryInsert);
                /****是否推荐****/
                if($push==1){
                    $min_chain_id=min($chains);
                    $users=Db::connect(Config::get('db_cq'))->table('cq_user')
                        ->where(['status'=>1])
                        ->where('find_in_set(:id,chains)',['id'=>$min_chain_id])
                        ->column('user_no');
                    if (!empty($users)){
                        $project=[];
                        foreach ($users as $k=>$user_no){
                            $project[$k]['user_no']=$user_no;
                            $project[$k]['project_name']= $data['company_name'];
                            $project[$k]['industry']=$data['industry_str'];
                            $project[$k]['image']=$data['logo'];
                            $project[$k]['city']=$data['city_str'];
                            $project[$k]['status']=1;
                            $project[$k]['is_read']=0;
                            $project[$k]['created_at']=$project[$k]['updated_at']=time();
                        }
                        Db::connect(Config::get('db_cq'))->table('cq_push_project')->insertAll($project);
                    }

                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                $msg  = "File：" . $e->getFile() . "\n";
                $msg .= "Line：" . $e->getLine() . "\n";
                $msg .= "Message：" . $e->getMessage() . "\n";
                var_dump($msg);
                // 回滚事务
                Db::rollback();
                $this->error('添加失败','add');
            }
            $this->success('添加成功','company_list');
        }

        $com_type=company_type(0);
        //产业链 城市 行业 list
        $label =new Label();
        $city=$label->city_list();
        $chain=$label->chain(0);
        $industry=$label->industry(0);
        $this->assign('chain',$chain);
        $this->assign('city',$city);
        $this->assign('industry',$industry);
        $this->assign('com_type',$com_type);

        return $this->fetch('add');
    }

    /**
     * 企业列表
     * @return mixed
     */
    public function company_list(Request $request)
    {
        $company_name=$request->param('company_name','','trim');
        $chain=$request->param('chain',0,'intval');
        /***企业基本信息***/
        $company_obj=db('companys a')
            ->field('a.id,a.company_name,a.industry_str,a.city_str')
            ->where(['a.status'=>1])
            ->order('id','desc');
        /***企业名称***/
        if (!empty($company_name)){
            $company_obj->where('a.company_name','like','%'.$company_name.'%');
        }
        /***产业链***/
        if (!empty($chain)){
            $company_obj->join('companys_chain b','a.id=b.company_id','left')
                ->where(['b.status'=>1,'b.chain_id'=>$chain]);
        }
        $company=$company_obj->paginate(['query' => request()->param()]);
        $this->view->assign('page', $company->render());
        $company= $company->toArray();
        foreach ($company['data'] as &$value){
            $value['industry_str']=str_replace("'",'"', $value['industry_str']);
            $value['city_str']=str_replace("'",'"', $value['city_str']);
            $chain_id=db('companys_chain')->where(['status'=>1,'company_id'=>$value['id']])->min('chain_id');
            $value['chain_name']=db('chain')->where(['status'=>1,'id'=>$chain_id])->value('chain_name');
            $value['industry_str']=implode('@',array_column(json_decode($value['industry_str'],true),'name'));
            $value['city_str']=implode('@',array_column(json_decode($value['city_str'],true),'name'));
        }

        $label =new Label();
        $chain=$label->chain(0);
        $this->view->assign('company', $company);
        $this->view->assign('chain', $chain);
        return $this->fetch('company_list');
    }

    /**
     * 企业详情
     * @return mixed
     */
    public function detail()
    {
        $id=$this->request->get('id',0,'intval');
        $company=db('companys a')
            ->join('parks b','a.park_id=b.id','left')
            ->field('a.*,b.park_name')
            ->where(['a.status'=>1,'a.id'=>$id])
            ->find();
        if (empty($company)){
            $this->error('获取失败','company_list');
        }
        $com_type=company_type(0);
        //产业链 城市 行业 list
        $label =new Label();
        $city=$label->city_list();
        $chain=$label->chain(0,3);
        $industry=$label->industry(0);


        $city_name=db('city')->whereIn('id',[$company['city_id'],$company['area_id']])->column('city_name','id');
        $chain_ids=db('companys_chain')->where(['status'=>1,'company_id'=>$id])->order('chain_id','asc')->column('chain_id');
        $industry_ids=db('companys_industry')->where(['status'=>1,'company_id'=>$id])->order('industry_id','asc')->column('industry_id');
        $company_industry=db('industry')->where('status',1)->whereIn('id',$industry_ids)->column('industry_name');
        $industry_str=implode('@',$company_industry);

        /***一个企业对应多个产业链***/
        $com_chain_info=db('chain')->where(['status'=>1])->whereIn('id',$chain_ids)->column('id,chain_name,pid,level,chain','id');
        $chain_data=[];
        foreach ($com_chain_info as $k=>$value){
            $chain_data[$value['chain']][$value['id']]['id']=$value['id'];
            $chain_data[$value['chain']][$value['id']]['name']=$value['chain_name'];
        }

        $chain_merge=[];
        foreach ($chain_data as $key=>$val) {
            $single_name = implode('@', array_column($val, 'name'));
            $single_id = implode(',', array_column($val, 'id'));
            $chain_merge[$key]['id']=$single_id;
            $chain_merge[$key]['name']=$single_name;
        }
        $chain_industry=[
            'chain_ids'=>$chain_ids,
            'chain_str'=>$chain_merge,
            'industry_ids'=>$industry_ids,
            'industry_str'=>$industry_str
        ];
        unset($chain_ids,$company_chian,$industry_ids,$company_industry);
        //dd($company);
        $this->assign([
            'company'=>$company,
            'chain'=>$chain,
            'city'=>$city,
            'industry'=>$industry,
            'com_type'=>$com_type,
            'city_name'=>$city_name,
            'ci'=>$chain_industry
        ]);
        return $this->fetch('detail');
    }

    /**
     * 企业编辑
     */
    public function edit(Request $request)
    {
        $data=$this->request->post();
        /****city_str*****/
        $city=array($data['province_id'],$data['city_id'],$data['area_id']);
        $city_str=[];
        $cityModel=db('city');
        foreach ($city as $id){
            if (!empty($id)){
                $name=$cityModel->where('id',$id)->value('city_name as name');
                $city_str[]=compact('id','name');
            }
        }
        /****industry_str*****/
        $industry_str=[];
        $industry_ids=[];
        $industry_data=$request->post()['industry'];
        $industryModel=db('industry');
        foreach ($industry_data as $id){
            if ($id){
                $name=$industryModel->where('id',$id)->value('industry_name as name');
                $industry_str[]=compact('id','name');
                array_push($industry_ids,$id);
            }
        }
        if (!empty($industry_str)){
            $data['industry_str']=json_encode($industry_str);
        }
        unset($data['industry']);
        /****chain****/
        $chain_data=$request->post()['chain'];
        $chains=[];
        foreach ($chain_data as $chain_id){
            if ($chain_id){
                $new_chain_id=explode(',',$chain_id);
                $chains=array_merge($chains,$new_chain_id);
            }
        }
        $chains=array_unique($chains);
        $chain_str=[];
        if (!empty($chains)){
            $bigChain=db('chain')->where(['status'=>1,'pid'=>0])->column('chain_name','id');
            foreach ($chains as $cc){
                if (in_array($cc,array_keys($bigChain))){
                    array_push($chain_str,$bigChain[$cc]);
                }
            }
            $data['chain_name']=implode(',',$chain_str);
        }
        unset($data['chain']);
        /****ipo****/
        if (isset($request->post()['ipo'])){
            $data['is_ipo']= in_array(1,$request->post()['ipo']) ? 1 :0;
            $data['is_inspect']= in_array(2,$request->post()['ipo']) ? 1 :0;
            $data['is_report']= in_array(3,$request->post()['ipo']) ? 1 :0;
            $data['is_market']= in_array(4,$request->post()['ipo']) ? 1 :0;
            unset($data['ipo']);
        }

        $data['com_type']=company_type($data['com_type']);
        $data['city_str']=json_encode($city_str);

        $chainInsert=[];
        $industryInsert=[];
        Db::startTrans();
        try {
            /****主表****/
            Db::table('yd_companys')->where('id', $data['id'])->update($data);
            /****chain****/
            $old = Db::table('yd_companys_chain')->where(['status' => 1, 'company_id' => $data['id']])->column('chain_id', 'id');
//                var_dump($old);
//                dd($chains);die();
            /***需要删除的id****/
            $del = [];
            foreach ($old as $k => $v) {
                if (!in_array($v, $chains)) {
                    array_push($del, $v);
                }
            }
            if (!empty($del)) {
                Db::table('yd_companys_chain')->where(['status' => 1, 'company_id' => $data['id']])->whereIn('chain_id', $del)->delete();
            }
            /***需要添加的数据的id****/
            foreach ($chains as $k => $id) {
                if (!in_array($id, $old)) {
                    $chainInsert[$k]['company_id'] = $data['id'];
                    $chainInsert[$k]['chain_id'] = $id;
                    $chainInsert[$k]['status'] = 1;
                }
            }
            if (!empty($chainInsert)) {
                Db::table('yd_companys_chain')->insertAll($chainInsert);
            }
            /****industry****/
            if (!empty($industry_ids)) {
                Db::table('yd_companys_industry')->where(['status' => 1, 'company_id' => $data['id']])->update(['status' => -1]);
                foreach ($industry_ids as $k=>$id){
                    $industryInsert[$k]['company_id']=$data['id'];
                    $industryInsert[$k]['industry_id']=$id;
                    $industryInsert[$k]['status']=1;
                }
                Db::table('yd_companys_industry')->insertAll($industryInsert);
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg  = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->error('修改失败','add');
        }
        $this->success('修改成功','company_list');
    }

    /**
     * 删除
     */
    public function del(Request $request){
        $id=$request->get('id',null,'intval');
        Db::startTrans();
        try {
            Db::table('yd_companys')->where(['status'=>1,'id'=>$id])->update(['status'=>-1]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg  = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->error('删除失败','company_list');
        }
        $this->success('删除成功','company_list');
    }


    /**
     * 添加企业工商数据
     * @return mixed
     */
    public function add_business(Request $request)
    {
        $company_id=$request->get('company_id',0,'intval');
        if ($request->isPost()){
            if (!$company_id){
                $this->error('添加失败','add_business');
            }
            /****industry_str*****/
            $industry_name=[];
            $industry_data=$request->post()['industry'];
            $industryModel=db('industry');
            foreach ($industry_data as $id){
                if ($id){
                    $name=$industryModel->where('id',$id)->value('industry_name as name');
                    array_push($industry_name,$name);
                }
            }
            $data=$request->post();
            $data['com_id']=$company_id;
            $data['industry']=implode('、',$industry_name);

            Db::startTrans();
            try {
                Db::table('yd_companys_business')->insert($data);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                $msg  = "File：" . $e->getFile() . "\n";
                $msg .= "Line：" . $e->getLine() . "\n";
                $msg .= "Message：" . $e->getMessage() . "\n";
                var_dump($msg);
                // 回滚事务
                Db::rollback();
                $this->error('添加失败','add_business',['company_id'=>$company_id]);
            }
            $this->success('添加成功','company_list');
        }
        $label =new Label();
        $industry=$label->industry(0);
        $this->assign('industry',$industry);
        return $this->fetch('addBusiness');
    }
}
